﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace wfTree
{
	public class FtPerson
	{
		public DbFtPerson PriPerson = new DbFtPerson();
		public DbFtPerson Spouse = new DbFtPerson();
		public DbFtPerson Father = new DbFtPerson();// = new DbFtPerson();
		public DbFtPerson Mother = new DbFtPerson();// = new DbFtPerson();
		public DbFtPerson Siblings; // = new DbFtPerson(); 
		public DbFtPerson Children;
		//public List<DbFtPerson> Parents = new List<DbFtPerson>();

		public FtPerson()
		{
		}

		public bool Exists
		{
			get
			{
				return PriPerson.Rows > 0;
			}
		}
		public bool HasSpouse
		{
			get
			{
				if (Spouse != null)
					if (Spouse.Rows > 0)
						return true;
				return false;
			}
		}
		public bool LoadPerson(long personId)
		{
			//Parents.Clear();
			//Siblings.Clear();

			bool ret = true;

			PriPerson.ClearValues();
			PriPerson.PersonId = personId;
			if (!PriPerson.Select())
				return false;

			// unknown person types cannot load parents and siblings
			if (PriPerson.Status == 2)
				return true;

			Spouse.ClearValues();
			Father.ClearValues();
			Mother.ClearValues();

			if (PriPerson.SpousePersonId != 0)
				loadPerson(PriPerson.SpousePersonId, ref Spouse);

			loadParents();
			loadSiblingsAndChildren();

			return ret;
		}

		private bool loadPerson(long personId, ref DbFtPerson person,  bool createIfNotExists = true)
		{
			person.ClearValues();

			if (personId > 0)
			{
				person.PersonId = personId;
				if (person.Select())
					return true;
			}

			person.ClearValues();
			person.Status = 2;
			person.Insert();

			return true;
		}

		private void loadParents()
		{
			bool update = false;
			// parents should exist to make sure siblings are linked. Can be unknown nodes.
			loadPerson(PriPerson.FatherPersonId, ref Father);

			if (Father.PersonId != PriPerson.FatherPersonId)
			{
				PriPerson.FatherPersonId = Father.PersonId;
				update = true;
			}

			loadPerson(PriPerson.MotherPersonId, ref Mother);

			if (Mother.PersonId != PriPerson.MotherPersonId)
			{
				PriPerson.MotherPersonId = Mother.PersonId;
				update = true;
			}

			if (update)
				PriPerson.Update();
		}

		private void loadSiblingsAndChildren()
		{
			Siblings = PriPerson.GetSiblings();
			Children = PriPerson.GetChildren();
		}
	}
}
